package com.study.lease.web.admin.custom.converter;

import com.study.lease.model.enums.BaseEnum;
import jdk.dynalink.linker.GuardedInvocation;
import jdk.dynalink.linker.GuardingTypeConverterFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.lang.invoke.MethodHandles;
import java.util.function.Supplier;
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {


    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return  new Converter<String, T>() {
            @Override
            public T convert(String code) {
                T[] enumConstants = targetType.getEnumConstants(); // 反射获取枚举数组
                for (T enumConstant : enumConstants){
                    if (enumConstant.getCode().equals(Integer.valueOf(code))){
                        return enumConstant;
                    }
                }

         throw new IllegalArgumentException(code+"非法参数");
     }
        };
    }
}
